using System.Threading.Tasks;
using System;
using System.IO;
using System.Text;
using UMC.Net;
using System.Net.WebSockets;

namespace UMC.Proxy
{

    class HttpsWebSocket : WebSocket
    {
        public byte[] buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(0x600);
        System.IO.Stream stream;
        public HttpsWebSocket(HttpMime mime, System.IO.Stream stream)
        {
            this.mime = mime;
            this.stream = stream;
            WebSocketRead();
        }
        public override void Receive(byte[] buffer, int offset, int size)
        {
            stream.Write(buffer, offset, size);

        }
        HttpMime mime;
        async void WebSocketRead()
        {
            int size = 0;
            try
            {
                while ((size = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    mime.Write(buffer, 0, size);
                }
            }
            catch
            {
                // this.Dispose();
                // return;
            }
            this.Dispose();
        }


        public override void Dispose()
        {
            this.mime.Dispose();
            stream.Close();
            stream.Dispose();
            if (buffer != null)
            {
                System.Buffers.ArrayPool<byte>.Shared.Return(buffer);
                buffer = null;
            }
        }

        protected override void Header(byte[] data, int offset, int size)
        {

        }
    }
}

